<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <!-- 下拉选择搜索框 -->
      <el-form-item label="搜索类型">
        <el-select v-model="selectedSearchType" placeholder="请选择搜索类型" style="width:100px" >
          <el-option label="书籍名称" value="bookName" />
          <el-option label="书籍ID" value="bookId" />
          <el-option label="用户名" value="userName" />
        </el-select>
        <!-- 统一搜索输入框 -->
        <el-form-item :prop="selectedSearchType">
          <el-input
            v-model="queryParams[selectedSearchType]"
            :placeholder="'请输入'+searchLabel"
            clearable
            style="width: 150px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
      </el-form-item>
      <!-- 状态搜索栏 -->
      <el-form-item label="状态">
        <el-cascader
          v-model="selectedValues"
          :options="options"
          placeholder="请选择"
          @change="handleStateChange"
          :show-all-levels="false"
          :props="{ expandTrigger: 'hover' , checkStrictly: true }"
          style="width: 150px;margin-right: 10px"
          clearable
          size="small"
        />
      </el-form-item>
      <!-- 借阅、归还时间搜索栏 -->
      <el-form-item label="借阅日期" prop="lendDate">
        <el-date-picker
          v-model="lendDate"
          type="date"
          style="width: 150px"
          placeholder="选择借阅日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="应还日期" prop="shouldBackTime">
        <el-date-picker
          v-model="shouldBackTime"
          type="date"
          style="width: 150px"
          placeholder="选择应还日期"
        >
        </el-date-picker>
      </el-form-item>
      <!-- 搜索、重置按钮 -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 增删改按钮 -->
    <el-row :gutter="10" class="mb8"> <!-- :gutter="10" -- 指定每一栏之间的间隔-->
      <!-- 增加按钮 -->
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <!-- 修改按钮 -->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <!-- 删除按钮 -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <!-- 隐藏搜索、刷新按钮 -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getBorrowList"></right-toolbar>
    </el-row>
    <!-- 借阅记录列表 -->
    <el-table
      v-loading="loading"
      :data="borrowListData"
      stripe
      :header-cell-style="{textAlign: 'center'}"
      :cell-style="{ textAlign: 'center' }"
      :default-sort="{prop:'lendId',order:'descending'}"
      @selection-change="handleSelectionChange">
      <!-- 表头 -->
      <el-table-column type="selection" fixed/>
      <el-table-column label="借阅编号" prop="lendId"         sortable/>
      <el-table-column label="书籍ID"  prop="bookId"         sortable/>
      <el-table-column label="书籍名称" prop="bookName"               />
      <el-table-column label="用户名"  prop="userName"        sortable/>
      <el-table-column label="借阅时间" prop="lendDate"       sortable/>
      <el-table-column label="应还时间" prop="shouldBackTime" sortable/>
      <el-table-column label="归还时间" prop="backDate"       sortable >
        <template slot-scope="data">
          <div v-if="data.row.backDate === null">------</div>
          <div v-if="data.row.backDate !== ''">{{ data.row.backDate }}</div>
        </template>
      </el-table-column>
      <el-table-column label="状态"    prop="state">
        <template slot-scope="data">
          <el-tag type="success" v-if="isBack(data.row)">已归还</el-tag>
          <el-tag type="warning" v-else-if="isLose(data.row)">已丢失</el-tag>
          <el-tag type="danger" v-else-if="isLate(data.row)">已逾期</el-tag>
          <el-tag type="info" v-else>未归还</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="已续借次数" prop="renewCount" width="100"/>
      <el-table-column label="操作" align="center" width="180" fixed="right" class-name="small-padding fixed-width" >
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button
            size="mini"
            type="primary"
            plain
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getBorrowList"
    />
    <!-- 添加或修改借阅记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" size="medium" label-width="100px">
        <!--第一行:书籍ID、图书名称-->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="书籍ID" prop="bookId">
              <el-input
                v-model="form.bookId"
                :disabled="isEdit"
                placeholder="请输入书籍ID"
                @change="getBookName"
                :style="{width: '100%'}"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图书名称" prop="bookName">
              <el-input
                v-model="form.bookName"
                :disabled="isEdit"
                placeholder="图书名称"
                :style="{width: '100%'}"
                clearable
                readonly
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!--第二行:用户ID、用户名-->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户ID" prop="userId">
              <el-input
                v-model="form.userId"
                :disabled="isEdit"
                placeholder="请输入用户ID"
                @change="getUserName"
                :style="{width: '100%'}"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
          <el-form-item label="用户名" prop="userName">
            <el-input
              v-model="form.userName"
              :disabled="isEdit"
              placeholder="用户名"
              :style="{width: '100%'}"
              clearable
              readonly
            />
          </el-form-item>
        </el-col>
        </el-row>
        <!--第三行:借阅时间、应还时间-->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="借阅时间" prop="lendDate">
              <el-date-picker
                v-model="form.lendDate"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="请选择借阅时间"
                @change="getLendDate()"
                :style="{width: '100%'}"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应还时间" prop="shouldBackTime">
              <el-date-picker
                v-model="form.shouldBackTime"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="请选择应还时间"
                :style="{width: '100%'}"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!--第四行:归还时间、是否归还-->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="归还时间" prop="backDate">
              <el-date-picker
                v-model="form.backDate"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="请选择归还时间"
                @change="getBackDate()"
                :style="{width: '100%'}"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否归还" prop="isBack">
              <el-radio-group v-model="form.isBack" size="medium" @input="getBack">
                <el-radio-button v-for="(item, index) in isBackOptions"
                                 :key="index"
                                 :label="item.value"
                                 >{{item.label}}</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!--第五行:续借次数、状态-->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="已续借次数" prop="renewCount">
              <el-input-number v-model="form.renewCount" :min="0" :max="3"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="state">
              <el-radio-group v-model="form.state" size="medium">
                <el-radio-button label="0" >未丢失</el-radio-button>
                <el-radio-button label="1"  v-if="form.isBack===1" disabled>已丢失</el-radio-button>
                <el-radio-button label="1"  v-else>已丢失</el-radio-button>
                <!--<el-radio-button v-for="(item, index) in stateOptions"-->
                <!--                 :key="index"-->
                <!--                 :label="item.value">{{item.label}}</el-radio-button>-->
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 弹窗按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {borrowList, addBorrowList, updateBorrowList, deleteBorrowList, getBookById} from "@/api/borrow/borrow";
import {listUser} from "@/api/system/user";
import {Message} from "element-ui";
import {setDisableNotification} from "@/utils/NotificationFlag";

export default {
  name: "borrow",
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bookName: undefined,
        bookId: undefined,
        userName: undefined,
        state: undefined,
        isBack:undefined,
        lendDate: '',
        shouldBackTime: ''
      },
      // 搜索类型默认选择图书名称
      selectedSearchType: 'bookName',
      // 显示搜索条件
      showSearch: true,
      // 借阅日期范围
      lendDate: '',
      // 应还日期范围
      shouldBackTime: '',
      // 初始化为空数组，用于存储用户选择的值
      selectedValues: [],
      //状态选项
      options: [
        //顶层选项：是否归还
        {
          value: '0', // 未归还的选项值
          label: '未归还', // 未归还的选项标签
          //子层选项
          children: [
            {
              value: '1', // 已丢失的选项值
              label: '已丢失', // 已丢失的选项标签
            },
          ],
        },
        {
          value: '1', // 已归还的选项值
          label: '已归还', // 已归还的选项标签
        },
      ],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 是否归还状态选项
      isBackOptions: [{
        "label": "未归还",
        "value": 0
      }, {
        "label": "已归还",
        "value": 1
      }],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        bookId: undefined,
        bookName: undefined,
        userId:undefined,
        userName: undefined,
        lendDate: undefined,
        backDate: null,
        shouldBackTime: null,
        isBack: 0,
        renewCount: 0,
        state: 0
      },
      // 是否禁用
      isEdit: false,
      // 表单校验
      rules: {
        bookId: [{
          required: true,
          message: '请输入书籍ID',
          trigger: 'blur'
        }],
        bookName: [],
        userId: [{
          required: true,
          message: '请输入用户ID',
          trigger: 'blur'
        }],
        userName: [],
        lendDate: [{
          required: true,
          message: '请选择借阅时间',
          trigger: 'change'
        }],
        shouldBackTime: [{
          required: true,
          message: '请选择应还时间',
          trigger: 'change'
        }],
        backDate: [],
        isBack: [],
        renewCount: [],
        state: []
      },
      // 禁止Notification弹窗
      disableNotification: true,
      // 遮罩层
      loading: true,
      // 表格高度
      tableFlexHeight:200,
      // 借阅记录表格数据
      borrowListData:[],
      // 总条数
      total: 0
    };
  },
  created() {
    this.getBorrowList();
  },
  methods: {
    /** 查询借阅记录列表 */
    getBorrowList() {
      this.loading = true
      borrowList(this.queryParams).then(res => {
        this.borrowListData = res.rows
        this.total = res.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      //如果日期为 null,则存储空字符串;否则,存储格式化后的日期字符串。
      this.queryParams.lendDate = this.lendDate == null ? '' : new Date(this.lendDate).toLocaleDateString().replaceAll('\\', '-')
      this.queryParams.shouldBackTime = this.shouldBackTime == null ? '' : new Date(this.shouldBackTime).toLocaleDateString().replaceAll('\\', '-')
      this.getBorrowList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.lendDate = '';
      this.shouldBackTime='';
      this.selectedValues=[];
      this.queryParams.isBack = undefined;
      this.queryParams.state = undefined;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 状态下拉框值改变操作 */
    handleStateChange(value){
      if (value[0]) {
        // 顶层选项发生变化
        this.queryParams.isBack = value[0]; // 是否归还的状态值
        this.queryParams.state = value[1] ? value[1] : null; // 已丢失的值，如果未选择则赋值为 null
      } else if (value[1]) {
        // 子选项发生变化
        this.queryParams.state = value[0]; // 更新是否丢失的值
      } else {
        // 清空后重置状态值
        this.queryParams.isBack = undefined; // 默认值为 undefined
        this.queryParams.state = undefined;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isEdit = false;
      this.title = "添加借阅记录";
      // 将借阅时间设置为今日日期
      this.form.lendDate=this.getNewDate()
      // 下一个月的同一天
      let nextMonth = new Date(new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate());
      // 将应还时间设置为一个月后,转换为YYYY-MM-DD格式
      this.form.shouldBackTime = nextMonth.toISOString().slice(0, 10);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const lendId = row.lendId || this.ids[0]
      borrowList(this.queryParams).then(response => {
        this.form = response.rows.find(row=>row.lendId===lendId);
        this.open = true;
        this.isEdit = true;
        this.title = "修改借阅记录";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const lendIds = row.lendId || this.ids.join(",")
      this.$modal.confirm('是否确认删除借阅编号为"' + lendIds + '"的数据项？').then(function () {
        return deleteBorrowList({lendIds : lendIds});
      }).then(() => {
        this.getBorrowList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.lendId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 判断展示借阅记录状态 */
    /** 判断是否归还 */
    isBack(data) {
      return data.isBack === 1
    },
    /** 判断是否丢失 */
    isLose(data) {
      return data.state === 1
    },
    /** 判断是否逾期 */
    isLate(data) {
      return this.getNewDate() > data.shouldBackTime
    },
    /** 获取今天日期(YYYY-MM-DD) */
    getNewDate() {
      let date = new Date()
      let mouth = ((date.getMonth() + 1) + '').length === 1 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)
      let day = (date.getDate() + '').length === 1 ? '0' + date.getDate() : date.getDate()
      return date.getFullYear() + '-' + mouth + '-' + day
    },
    /** 匹配图书名称 */
    getBookName() {
      // 如果输入框的图书Id为空，将图书名称设置''
      if (!this.form.bookId) {
        this.form.bookName = '';
        return;
      }
      let bookId = this.form.bookId;
      //禁用Notification弹窗条件为true
      setDisableNotification(true);
      // 调用后端接口查询图书名称
      getBookById(bookId).then(response => {
        // 将获取到的图书名称设置到表单中
        this.form.bookName = response.data.data.name;
        //禁用Notification弹窗条件为false
        setDisableNotification(false);
      }).catch(error=>{
        Message({ message: '请输入有效的图书ID', type: 'error' });
        // 将书籍Id设为空字符串
        this.form.bookId='';
        setDisableNotification(false);
      });
    },
    /** 匹配用户名 */
    getUserName() {
      // 确保用户Id不为空才发送请求
      if (this.form.userId) {
        let userData = {}
        // 调用后端接口查询用户名
        listUser({ userId: this.form.userId }).then(response => {
          userData = response.rows[0];
          // 确保数据有效并且包含用户名属性
          if (userData) {
            // 将获取到的用户名设置到表单中
            this.form.userName = userData.userName;
          }else{
            Message({ message: '请输入有效的用户ID', type: 'error' });
            // 将用户Id设为空字符串
            this.form.userId='';
          }
        });
      } else {
        // 如果用户Id为空，将用户名设置为空字符串。
        this.form.userName = '';
      }
    },
    /** 根据借阅时间获得应还时间 */
    getLendDate(){
      if(this.form.lendDate){
        // 获得借阅时间
        let lendDate=new Date(this.form.lendDate)
        // 下一个月的同一天
        let nextMonth = new Date(lendDate.getFullYear(), lendDate.getMonth() + 1, lendDate.getDate());
        // 将应还时间设置为一个月后,转换为YYYY-MM-DD格式
        this.form.shouldBackTime = nextMonth.toISOString().slice(0, 10);
      }
      // 如果借阅时间为空
      else{
        // 如果应还时间有值，保持不变;如果没有值，将其设置为空字符串。
        this.form.shouldBackTime = this.form.shouldBackTime || '';
      }
    },
    /** 监听是否归还按钮切换状态 */
    getBack(){
      //当切换状态为已归还且归还日期为空时
      if(this.form.isBack===1 && this.form.backDate===null){
        //给归还日期赋值今日日期
        this.form.backDate=this.getNewDate()
      }
      //当切换状态为未归还时
      else if(this.form.isBack===0){
        //给归还日期赋值空
        this.form.backDate=null
      }
      //设图书是否丢失为未丢失
      this.form.state=0
    },
    /** 归还日期是否选定值 */
    getBackDate(){
      //当归还日期为空时，是否归还按钮切换为未归还
      if (this.form.backDate===null){
        this.form.isBack=0
      }
      //不为空，切换为已归还
      else{
        this.form.isBack=1
      }
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        //判断应还时间和借阅时间的大小
        if (this.form.lendDate && this.form.shouldBackTime) {
          const lendDate = new Date(this.form.lendDate);
          const shouldBackTime = new Date(this.form.shouldBackTime);
          if (shouldBackTime < lendDate) {
            this.$message.error('应还时间不能小于借阅时间！');
            return false; // 返回 false 表示验证失败
          }
        }
        //判归还时间和借阅时间的大小
        if (this.form.lendDate && this.form.backDate) {
          const lendDate = new Date(this.form.lendDate);
          const backDate = new Date(this.form.backDate);
          if(backDate < lendDate){
            this.$message.error('归还时间不能小于借阅时间！');
            return false; // 返回 false 表示验证失败
          }
        }
        if (valid) {
          //当存在lendId，显示修改记录表单
          if (this.form.lendId !== undefined) {
            updateBorrowList(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getBorrowList();
            }).catch(() =>{
              Message({ message: '修改失败', type: 'error' });
            });
          }
          //否则，显示增加记录表单
          else {
            addBorrowList(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getBorrowList();
            }).catch(() =>{
              Message({ message: '新增失败', type: 'error' });
            });
          }
        }
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        bookId: undefined,
        bookName: undefined,
        userId: undefined,
        userName: undefined,
        lendDate: null,
        backDate: null,
        shouldBackTime: null,
        isBack: 0,
        renewCount: 0,
        state: 0
      };
      this.resetForm("form");
    }
  },
  watch:{
    //表单填写变化
    form: {
      immediate: true, // 立即执行一次回调函数，监听变化
      handler(newVal, oldVal) {
        // 图书Id发生改变时调用方法获取图书名称
        if (newVal.bookId !== oldVal.bookId) {
          this.getBookName();
        }
        // 用户Id发生改变时调用方法获取用户名
        if (newVal.userId !== oldVal.userId) {
          this.getUserName();
        }
      }
    }
  },
  computed: {
    // 根据选择的搜索类型动态设置label
    searchLabel() {
      return this.selectedSearchType === 'bookName'
        ? '书籍名称'
        : this.selectedSearchType === 'bookId'
          ? '书籍ID'
          : '用户名';
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
//操作列的修改删除按钮
.el-table .fixed-width .el-button--mini {
  padding-left: 10px;
  padding-right: 10px;
}
//状态搜索下拉框的高度
.el-cascader-panel{
  height: 80px!important
}
</style>
